from reboot import Message
from uiautomation import WindowControl, MenuControl  # 导入自动化控制相关模块
import json, sys, time, random, hashlib, os, pythoncom
from PyQt5.QtGui import QIcon, QPixmap
from Form import Ui_Form
from PyQt5 import QtWidgets
import threading
from tkinter import simpledialog
from tkinter import Tk
from datetime import datetime

ver_code = random.randint(1000, 9999)


class App:
    status = True

    def __init__(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.window = QtWidgets.QMainWindow()
        self.window.resize(595, 672)
        self.window.setFixedSize(595, 672)
        icon = QIcon()
        icon.addPixmap(QPixmap('icon.png'))
        self.window.setWindowIcon(icon)
        self.win = Ui_Form()
        self.win.setupUi(self.window)
        self.win.pushButton_2.clicked.connect(lambda: self.thread_start(self.start_click))
        self.win.pushButton_3.clicked.connect(lambda: self.thread_start(self.stop_click))
        self.window.show()
        sys.exit(self.app.exec_())

    def thread_start(self, func, *args):
        t = threading.Thread(target=func, args=args)
        t.setDaemon(True)
        t.start()

    def start_click(self):
        self.win.textBrowser.append('已开启机器人'.center(45, '*'))
        self.status = True

        wx = WindowControl(Name="微信", searchDepth=1)  # 绑定名为微信的主窗口控件
        wx.SwitchToThisWindow()  # 切换窗口
        hw = wx.ListControl(Name="会话")  # 寻找会话控件绑定
        while True:  # 循环等待消息
            we = hw.TextControl(searchDepth=4)  # 查找未读消息
            if we.Name:  # 加入存在未读消息
                we.Click(simulateMove=False)  # 点击未读消息
                last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name  # 读取最后一条消息
                msg = Message(last_msg)
                now = datetime.now().strftime('%H:%M:%S')
                self.win.textBrowser.append(f'Time：{now}\n收到消息：{last_msg}\n发送消息：{msg}')
                if msg:  # 判断是否有关键词内容，如果有，则执行以下代码
                    wx.SendKeys(msg, waitTime=0)  # 将结果输入文字框
                    wx.SendKeys("{Enter}", waitTime=0)  # 回车发送消息
                    wx.TextControl(SubName=msg[0][:5]).RightClick()  # 通过消息匹配检索会话栏中的联系人并右击
                else:  # 如果没有关键词内容，则执行以下代码
                    wx.TextControl(SubName=last_msg[:5]).RightClick()
                ment = MenuControl(ClassName="CMenuWnd")  # 匹配右击控件
                ment.TextControl(Name="不显示聊天").Click()  # 点击右击控件中的不显示聊天

    def stop_click(self):
        self.win.textBrowser.clearFocus()
        self.win.textBrowser.append('已关闭机器人'.center(45, '*'))
        self.win.textBrowser.ensureCursorVisible()
        self.status = False
        print(self.status)


def activa():
    tk = Tk()
    tk.geometry('400x300')
    tk.withdraw()
    text = simpledialog.askstring(title='软件激活', prompt=f'软件激活\n您的验证码为：{ver_code}')
    tk.destroy()
    return text


if __name__ == '__main__':
    path = 'D:/Program Files/a'
    if not os.path.exists(path):
        text = activa()
        pwd = ver_code * 100 - 30 % 10
        hib = hashlib.md5()
        hib.update(str(pwd).encode('utf-8'))
        password = hib.hexdigest()[:4]
        if text == password:
            os.mkdir(path)
            App()
        else:
            sys.exit()
    else:
        App()
